/**
 * 581. 最短无序连续子数组
 * https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
 */

// /**
//  * @param {number[]} nums
//  * @return {number}
//  */
// function findUnsortedSubarray(nums) {
//   const numsResolved = Array.from(nums);
//   numsResolved.sort((a, b) => a - b);
//   let left = 0;
//   let right = nums.length - 1;
//   while (nums[left] === numsResolved[left] && left < nums.length) {
//     left += 1;
//   }
//   while (nums[right] === numsResolved[right] && right > left) {
//     right -= 1;
//   }
//   if (right > left) {
//     return right - left + 1;
//   }
//   return 0;
// }

/**
 * @param {number[]} nums
 * @return {number}
 */
function findUnsortedSubarray(nums) {
  let left = 0;
  let right = nums.length - 1;
  while (left < right && nums[left] <= nums[left + 1]) {
    left += 1;
  }
  left += 1;
  while (right > left && nums[right] >= nums[right - 1]) {
    right -= 1;
  }
  right -= 1;
  if (right < left - 1) {
    return 0;
  }
  let min = nums[left];
  let max = min;
  let num = 0;
  for (let i = left + 1; i <= right; i += 1) {
    num = nums[i];
    if (num < min) {
      min = num;
    }
    if (num > max) {
      max = num;
    }
  }
  left -= 1;
  right += 1;
  min = Math.min(nums[right], min);
  max = Math.max(nums[left], max);
  for (; left >= 0; left -= 1) {
    if (nums[left] <= min) {
      break;
    }
  }
  left += 1;
  for (; right < nums.length; right += 1) {
    if (nums[right] >= max) {
      break;
    }
  }
  right -= 1;
  return right - left + 1;
}

console.log(findUnsortedSubarray([2, 6, 4, 8, 10, 9, 15]) === 5);
console.log(findUnsortedSubarray([1, 2, 3, 4]) === 0);
console.log(findUnsortedSubarray([1]) === 0);
console.log(findUnsortedSubarray([2, 1]) === 2);
